package com.itsm.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.itsm.common.util.JwtUtil;
import com.itsm.gateway.config.TokenWhiteConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


@Component
public class JwtCheckFilter implements GlobalFilter , Ordered {

    @Autowired
    private TokenWhiteConfig tokenWhiteConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //验证是否需要token
        if(!isRequireToken(exchange)){
            //不需要token直接放行
            return chain.filter(exchange);
        }
        String token  = getUserToken(exchange);
        try{
            JwtUtil.verify(token);
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            return buildNoAuthorization(exchange,HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error","签名不一致");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            return buildNoAuthorization(exchange,HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error","令牌过期");

        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            return buildNoAuthorization(exchange,HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error","算法不一致");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            return buildNoAuthorization(exchange,HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error","失效的payload");
        }catch (Exception e){
            e.printStackTrace();
            return buildNoAuthorization(exchange,HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error","token无效");
        }

        if(StringUtils.isEmpty(token) ){
            return buildNoAuthorization(exchange);
        }else{
            return chain.filter(exchange);
        }
    }

    private Mono<Void> buildNoAuthorization(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error","NoAuthorization");
        jsonObject.put("errorMsg","Token is null or error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }
    private Mono<Void> buildNoAuthorization(ServerWebExchange exchange, HttpStatus code, String error, String errorMsg) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(code);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error",error);
        jsonObject.put("errorMsg",errorMsg);
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }

    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst("token");

        return token == null ? null : token.replace("bearer","") ;
    }

    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if(tokenWhiteConfig.getWhiteList().contains(path)){
            return false;
        }
        return true;
    }


    @Override
    public int getOrder() {
        return 0;
    }

}
